﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
using DevExpress.XtraCharts;
using XChip_Common;
using SerialPortHelperLib;
using System.Windows.Forms.DataVisualization.Charting;
using XChipTool.Enties;
using Newtonsoft.Json;
using System.Threading;
using System.IO;
using System.Configuration;
using BinAnalysisHelp;
using AdbService;

namespace XChipTool
{
    public partial class XChip_GAMMA : DevExpress.XtraEditors.XtraUserControl
    {
        public SerialPort sPortTemp;
        private bool isRead = false;
        private bool isWrite = false;
        List<ucsDouble> listucs = new List<ucsDouble>();
        long[] list_64 = new long[65];
        //记录x九个点的索引
        //int tempXKey = 0;

        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;

        public  gammahistoryManager gammaM ;

        bool startMove = false;


        private List<addressregister> XChipAe;
        private List<addressregister> XChipGamma;
        private addressregisterManager aBll;
        private string radiostr = string.Empty;

        private static XChip_GAMMA _instance;
        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;

        public static XChip_GAMMA Instance(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            if (_instance == null)
            {
                _instance = new XChip_GAMMA(_sPortTemp, _aBll);
            }
            return _instance;
        }

        public XChip_GAMMA()
        {
            InitializeComponent();
        }

        public XChip_GAMMA(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
              sPortTemp = _sPortTemp;
              aBll = _aBll;
            XChipAe = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "ae" || c.Classify == "Common"));
            XChipGamma = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "gamma" || c.Classify == "Common"));
            InitializeComponent();
        }

        private void XChip_GAMMA_Load(object sender, EventArgs e)
        {

            //if (ConfigurationManager.AppSettings["xcEdition"] == "1") {
            //    simpleButton5.Text = "获取参数";
            //    simpleButton10.Text = "调式指南";
            //    simpleButton9.Text = "保存参数";
            //    simpleButton8.Text = "发送";
            //    simpleButton7.Text = "清空";
            //    COMBO_GAMMAPRE.Properties.NullText = "曲线选择";
            //    gamma_curve.Properties.Items[0].Description = "Rgb 曲线";
            //    gamma_curve.Properties.Items[1].Description = "Raw 曲线";
            //    gamma_curve.Properties.Items[2].Description = "YUV 曲线";

            //    gammaStateEn.Items[0].Description = "RGB Gamma 使能";
            //    gammaStateEn.Items[1].Description = "RAW Gamma 使能";
            //    gammaStateEn.Items[2].Description = "YUV Gamma 使能";
            //    checkedListBoxControl1.Items[0].Description = "场景切换使能";
            //    checkedListBoxControl1.Items[1].Description = "调试";

            //    DayMode.Properties.Items[0].Description = "白天";
            //    DayMode.Properties.Items[1].Description = "晚上";
            //    DayMode.Properties.Items[2].Description = "极夜";

            //    label24.Text = "参考曲线：";
            //    labelControl9.Text = "边缘增强_低增益";
            //    labelControl13.Text = "边缘增强_中亮度";
            //    labelControl1.Text = "边缘增益_高亮度";
            //    LookHistory.Visible = false;
            //}

            chart1.Legends.Clear();
            chart1.Titles.Add("右键点击可删除黑点");
            var ser = chart1.Series[0];

            ser.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline;
            ser.BorderWidth = 2;
            ser.Color = Color.Red;
   
            RefreshChart();
 
            var chartArea = chart1.ChartAreas[0];

            chartArea.AxisX.Minimum = 0;

            chartArea.AxisX.Maximum = 256;

            chartArea.AxisY.Minimum = 0d;

            chartArea.AxisY.Maximum = 256;


            List<TreeListValue> GammaList = new List<TreeListValue>();
            GammaList.Add(new TreeListValue() { DisplayMember = "YUV Gamma配置1", ValueMember = "0" });
            GammaList.Add(new TreeListValue() { DisplayMember = "YUV Gamma配置2", ValueMember = "1" });
            GammaList.Add(new TreeListValue() { DisplayMember = "YUV Gamma配置3", ValueMember = "2" });
            COMBO_GAMMAPRE.Properties.ValueMember = "ValueMember";
            COMBO_GAMMAPRE.Properties.DisplayMember = "DisplayMember";
            COMBO_GAMMAPRE.Properties.DataSource = GammaList;
            COMBO_GAMMAPRE.ItemIndex = -1;

        }
        /// <summary>
        /// 鼠标点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chart1_MouseClick(object sender, MouseEventArgs e)
        {
            //表示已经最大化点数
            //if (list.Count >= 9) return;
            var ser = chart1.Series[0];
            if (e.Button == MouseButtons.Left)
            {
               

            }
            if (e.Button == MouseButtons.Right) //右键 弹出框
            {
                var myTestResult = chart1.HitTest(e.X, e.Y);
                if (myTestResult.ChartElementType == System.Windows.Forms.DataVisualization.Charting.ChartElementType.DataPoint)
                {
                    //this.Cursor = Cursors.Cross;
                    int i = myTestResult.PointIndex;
                    var dp = myTestResult.Series.Points[i];

                    double doubleXValue = (dp.XValue);
                    double doubleYValue = dp.YValues[0];
                    if ((doubleXValue == 255 && doubleYValue ==255)||(doubleXValue == 0 && doubleYValue == 0))  //起始点和结束点跳过
                    {
                        return;
                    }

                    //int sysIndex = list.FindIndex(c => c.xValue == (int)doubleXValue && c.yValue == (int)doubleYValue);
                    int sysIndex = listucs.FindIndex(c => c.xValue >= doubleXValue - 5 && c.xValue <= doubleXValue + 5 && c.yValue >= doubleYValue - 5 && c.yValue <= doubleYValue + 5);
                    if (sysIndex >= 0)
                    {
                        listucs.RemoveAt(sysIndex);
                    }
                    ser.Points.Clear();
                    //清空显示xy值文本框
                    GAMMA_X.Text = string.Empty;
                    GAMMA_Y.Text = string.Empty;
                    RefreshChart();
                }
               
            }

          

        }
        void GammaListRemove(int x, int y)
        {
            //var tt = list.Where(c => c.xValue > (x - 10) && c.xValue < RangeMax).ToList();
            var tt = listucs.Where(c => c.xValue > RangeMin && c.xValue < RangeMax).ToList();
            foreach (var item in tt)
            {
                //if (item.xValue != RangeMin)
                //{
                listucs.Remove(item);
                //}

            }
            if (x > RangeMin+3 && x < RangeMax-3)
            {
                listucs.Add(new ucsDouble() { xValue = x, yValue = y, Col = Color.Black });
            }

            if (x==0 && (y>=0))
            {
                listucs.Remove(listucs.Find(c => c.xValue == 0));
                listucs.Add(new ucsDouble() { xValue = x, yValue = y, Col = Color.Black });
            }
            if (x==255 && (y<=255))
            {
                listucs.Remove(listucs.Find(c => c.xValue == 255));
                listucs.Add(new ucsDouble() { xValue = x, yValue = y, Col = Color.Black });
            }
           
        }
        /// 1表示0-32 2表示32-64 3表示64-96 4表示96-128 5表示128-160 6表示160-192 7表示192-224 8表示224-255
        /// 10表示32 11表示64 12表示96  13表示128 14表示160 15表示192 16表示224
        /// <summary>
        /// 存储在那个范围的值 
        /// 1表示0-16 2表示16-32 3表示32-48 4表示48-64 5表示64-96 6表示96-128 7表示128-192 8表示192-255
        /// 10表示16 11表示32 12表示48  13表示64 14表示96 15表示128 16表示192
        /// </summary>
        //int RangeTemp = -1;

        int RangeMax = -1;
        int RangeMin = -1;

        /// <summary>
        /// 鼠标按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chart1_MouseDown(object sender, MouseEventArgs e)
        {
            startMove = true;
            //符合条件就添加点位
            if (e.Button == MouseButtons.Left)
            {
                //if (list.Count > 7) return;
                double _xValue = -1;
                double _yValue = -1;

                #region 注释
                //var myTestResult = chart1.HitTest(e.X, e.Y);

                //if (myTestResult.ChartElementType == System.Windows.Forms.DataVisualization.Charting.ChartElementType.DataPoint)
                //{
                //    this.Cursor = Cursors.Cross;
                //    int i = myTestResult.PointIndex;
                //    var dp = myTestResult.Series.Points[i];

                //    double doubleXValue = (dp.XValue);
                //    double doubleYValue = dp.YValues[0];


                //    if (doubleXValue == 32 || doubleXValue == 64 || doubleXValue == 96 || doubleXValue == 128 || doubleXValue == 160 || doubleXValue == 192 || doubleXValue == 224)
                //    {
                //        int sysIndex = list.FindIndex(c => c.xValue == (int)doubleXValue && c.yValue == (int)doubleYValue);
                //        if (sysIndex >= 0)
                //        {
                //            list.RemoveAt(sysIndex);
                //        }
                //        if (doubleXValue == 32)
                //        {
                //            RangeTemp = 10;
                //        }
                //        else if (doubleXValue == 64)
                //        {
                //            RangeTemp = 11;
                //        }
                //        else if (doubleXValue == 96)
                //        {
                //            RangeTemp = 12;
                //        }
                //        else if (doubleXValue == 128)
                //        {
                //            RangeTemp = 13;
                //        }
                //        else if (doubleXValue == 160)
                //        {
                //            RangeTemp = 14;
                //        }
                //        else if (doubleXValue == 192)
                //        {
                //            RangeTemp = 15;
                //        }
                //        else if (doubleXValue == 224)
                //        {
                //            RangeTemp = 16;
                //        }

                //    }


                //    //ser.Points.Clear();
                //}
                //else
                //{ 
                #endregion
                var area = chart1.ChartAreas[0];
                try
                {
                    _xValue = (int)area.AxisX.PixelPositionToValue(e.X);
                    _yValue = area.AxisY.PixelPositionToValue(e.Y);
                }
                catch (Exception)
                {
                    return;
                }

                RangeMin = listucs.Where(c => c.xValue < ((_xValue - 5) < 1 ? 1 : _xValue - 5)).Max(c => c.xValue);
                RangeMax = listucs.Where(c => c.xValue > ((_xValue + 5) > 254 ? 254 : _xValue + 5)).Min(c => c.xValue);

                int sysIndex = listucs.FindIndex(c => c.xValue > RangeMin && c.xValue < RangeMax);
                if (sysIndex >= 0)
                {
                    listucs.RemoveAt(sysIndex);
                }


            }


        }
        /// <summary>
        /// 鼠标抬起
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chart1_MouseUp(object sender, MouseEventArgs e)
        {
            startMove = false;
        
           
        }
        /// <summary>
        /// 鼠标移动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chart1_MouseMove(object sender, MouseEventArgs e)
        {            
            var ser = chart1.Series[0];
            double _xValue = -1;
            double _yValue = -1;
            var area = chart1.ChartAreas[0];

            try
            {
                _xValue = area.AxisX.PixelPositionToValue(e.X);
                _yValue = area.AxisY.PixelPositionToValue(e.Y);
            }
            catch (Exception)
            {
                return;
            }
            if (_xValue<256 &&_xValue>-1&&_yValue<256&&_yValue>-1)
            this.Cursor = Cursors.Cross;
            else this.Cursor = Cursors.Arrow;
            if (startMove)
            {
                if (e.Button == MouseButtons.Left)
                {
                    
                  
                    
                    if (_xValue>255)
                    {
                        _xValue = 255;
                    }                   
                    if (_yValue>255)
                    {
                        _yValue = 255;
                    }
                    if (_xValue < 0)
                    {
                        _xValue = 0;
                    }
                    if (_yValue < 0)
                    {
                        _yValue = 0;
                    }
                    //if (list.Count <= 0)
                    //{
                       
                        GammaListRemove((int)_xValue, (int)_yValue);
                        //list.Add(new ucsDouble() { xValue = (int)_xValue, yValue = (int)_yValue });
                    //}
                    //显示xy值文本框
                    GAMMA_X.Text = ((int)_xValue).ToString();
                    GAMMA_Y.Text = ((int)_yValue).ToString();
                    listucs = listucs.Distinct(new ModelComparer()).ToList();
                   
                    RefreshChart();
                }
             
            }            
        }
        /// <summary>
        /// 刷新界面
        /// </summary>
        void RefreshChart()
        {
            var ser = chart1.Series[0];
            ser.Points.Clear();
            //记录要删除的集合
            List<ucsDouble> listTemp = new List<ucsDouble>();
            //foreach (var item in listucs)
            //{
            //    if (item.xValue == 0 && item.yValue == 0)
            //    {
            //        listTemp.Add(item);
            //    }
            //    if (item.xValue == 255 && item.yValue <= 255) //消除旁边y所有点位
            //    {
            //        listTemp.Add(item);
            //    }


            //}

            //////删除记录点位
            //foreach (var item in listTemp)
            //{
            //    listucs.Remove(item);
            //}

            //listTemp = new List<ucsDouble>();
            //listTemp.Add(new ucsDouble() { xValue = 0, yValue = 0, Col = Color.Red });
            //listTemp.Add(new ucsDouble() { xValue = 255, yValue = 255, Col = Color.Red });

            //listTemp.AddRange(listucs);
            //listucs.Add(new ucsDouble() { xValue = 0, yValue = 0, Col = Color.Red });
            //listucs.Add(new ucsDouble() { xValue = 255, yValue = 255, Col = Color.Red });
            //检查存在 0,0 255,255
            //检查 0,1表示0-16    8表示192-255,255
            if (!listucs.Exists(c=>c.xValue == 0  ))
            {
                listucs.Add(new ucsDouble() { xValue = 0, yValue = 0, Col = Color.Red });
            }
            if (!listucs.Exists(c => c.xValue == 255 ))
            {
                listucs.Add(new ucsDouble() { xValue = 255, yValue = 255, Col = Color.Red });
            }
           


            listTemp.AddRange(listucs);

            listTemp = listTemp.OrderBy(c => c.xValue).ToList();
            //listTemp.Add(new ucsDouble() { xValue = int.Parse(GAMMA_X.Text), yValue = int.Parse(GAMMA_Y.Text) });
            list_64 = new long[65];
            int[] arrList ={0,2,4,6,8,10,12,14,16,
                        18,20,22,24,26,28,30,32,
                        34,36,38,40,42,44,46,48,
                        50,52,54,56,58,60,62,64,
                        68,72,76,80,84,88,92,96,
                        100,104,108,112,116,120,124,128,
                        136,144,152,160,168,176,184,192,
                        200,208,216,224,232,240,248,254};


            double[] spz = new double[256];
            if (listucs.Count == 2)
            {
                var num = listucs.Last().xValue - listucs.First().xValue;
                for (int i = 0; i < num + 1; i++)
                {
                    spz[i] = i;
                }
            }
            else {
                Lagrange ltemp = new Lagrange(listTemp.Select(c => c.xValue).ToArray(), listTemp.Select(c => (double)c.yValue).ToArray());
                spz = ltemp.Spline();
            }
            for (int i = 0; i < 65; i++)
            {
                if (!listucs.Exists(c => c.xValue == arrList[i]))
                {
                    listTemp.Add(new ucsDouble() { xValue = arrList[i], yValue = (int)Lagrange.CLIP_RANGE(spz[arrList[i]], 0, 255) });                    
                }              
                list_64[i] = (int)Lagrange.CLIP_RANGE(spz[arrList[i]], 0, 255);                                
            }
          
          

            var listT = listTemp.OrderBy(c => c.xValue).ToList();
           
            for (int i = 0; i < listT.Count(); i++)
            {
                ser.Points.AddXY(listT[i].xValue, listT[i].yValue);
                ser.Points[i].MarkerColor = listT[i].Col;
            }

           
        }


        #region 去掉重复数据
        /// <summary>
        /// 去掉重复数据
        /// </summary>
        public class ModelComparer : IEqualityComparer<ucsDouble>
        {
            public bool Equals(ucsDouble x, ucsDouble y)
            {
                return x.xValue == y.xValue;
            }
            public int GetHashCode(ucsDouble obj)
            {
                return obj.xValue.GetHashCode();
            }
        }
        /// <summary>
        /// 去掉已有数据重复数据
        /// </summary>
        public class PointComparer : IEqualityComparer<System.Windows.Forms.DataVisualization.Charting.DataPoint>
        {
            public bool Equals(DataPoint x, DataPoint y)
            {
                return x.XValue == y.XValue && x.YValues[0] == y.YValues[0];
            }

            public int GetHashCode(DataPoint obj)
            {
                return obj.GetHashCode();
            }
        }

        #endregion
        #region 清理按钮
        private void simpleButton7_Click(object sender, EventArgs e)
        {
            //显示xy值文本框
            GAMMA_X.Text = string.Empty;
            GAMMA_Y.Text = string.Empty;

            chart1.Legends.Clear();
            listucs.Clear();
            var ser = chart1.Series[0];
            ser.Points.Clear();
            ser.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline;
            ser.BorderWidth = 2;
            ser.Color = Color.Red;
            listucs.Add(new ucsDouble() { xValue = 0, yValue = 0 });
            listucs.Add(new ucsDouble() { xValue = 255, yValue = 255 });
            //初始化list集合
            list_64 = new long[65];
            //list_64[0x0] = 0x0;
            //list_64[0x40] = 0xff;
            //foreach (var item in list)
            //{
            //    ser.Points.AddXY(item.xValue, item.yValue);
            //}
            RefreshChart();
        } 
        #endregion
        #region Get获取
        /// <summary>
        /// 点击获取值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton5_Click(object sender, EventArgs e)
        {

          
            
            WaitBefore.Start("读取中", "正在加载中", 10);
            list_64 = new long[65];
            isRead = true;
            long nDaymode = 0;
            var nMask = await GetAERegister("Scene_Switch_En"); //SerialSend.ReadRegister(0x80140047, sPortTemp);
            if (nMask == 0)
            {
                nDaymode = 0;
            }
            else
            {
                nMask = await GetAERegister("Scene_Mode");
                nMask &= 0x3;
                if (nMask == 0)
                {
                    nDaymode = 1;
                    radiostr = "_Day";
                }
                else if (nMask == 1)
                {
                    nDaymode = 2;
                    radiostr = "_Night";
                }
                else
                {
                    nDaymode = 3;
                    radiostr = "_Midnight";
                }
            }
            
            
           

            //((int)nDaymode);
            //给曲线图赋值
            //chart1.Legends.Clear();
            var ser = chart1.Series[0];
            ser.Points.Clear();
            listucs.Clear();
            long nValue = 0;
            //存疑不确定注释掉是不是对的先记录
            nDaymode = 0;//绘图默认用8030下的寄存器绘图
            List<ucsDouble> listT = new List<ucsDouble>();
            for (int i = 0; i < 65; i++)
            {
                if (i == 0 || i == 0x8 || i == 0x10 || i == 0x18 || i == 0x20 || i == 0x28 || i == 0x30 || i == 0x38 || i == 0x40)
                //if (i == 0 || i == 0x10 || i == 0x20 || i == 0x28 || i == 0x30 || i == 0x34 || i == 0x38 || i == 0x3C || i == 0x40)
                {
                    //gamma_curve
                    switch (gamma_curve.SelectedIndex)
                    {
                        case 0:
                            {
                                if (nDaymode == 0)
                                {
                                    nValue =await GetGammaRegister($"RGB_GammaList_{i}");//SerialSend.ReadRegister((ulong)(0x80300000 | 0x1400 + i), sPortTemp);
                                }
                                else if (nDaymode == 1)
                                {
                                    nValue = await GetGammaRegister($"RGB_GammaList_Day_{i}");//SerialSend.ReadRegister((ulong)(0x80140000 | 0x359 + i), sPortTemp);
                                }
                                else if (nDaymode == 2)
                                {
                                    nValue = await GetGammaRegister($"RGB_GammaList_Night_{i}");//SerialSend.ReadRegister((ulong)(0x80140000 | 0x39a + i), sPortTemp);
                                }
                                else if (nDaymode == 3)
                                {
                                    nValue = await GetGammaRegister($"RGB_GammaList_Midnight_{i}");// SerialSend.ReadRegister((ulong)(0x80140000 | 0x3db + i), sPortTemp);
                                }
                                //给list 赋值
                                AddGammaPoint(i, (int)nValue);
                            }
                            break;
                        case 1:
                            {
                                if (nDaymode == 0)
                                {
                                    nValue = await GetGammaRegister($"RAW_GammaList_{i}");// SerialSend.ReadRegister((ulong)(0x80300000 | 0x900 + i), sPortTemp);
                                }
                                else if (nDaymode == 1)
                                {
                                    nValue = await GetGammaRegister($"RAW_GammaList_Day_{i}");// SerialSend.ReadRegister((ulong)(0x80140000 | 0x41c + i), sPortTemp);
                                }
                                else if (nDaymode == 2)
                                {
                                    nValue = await GetGammaRegister($"RAW_GammaList_Night_{i}");// SerialSend.ReadRegister((ulong)(0x80140000 | 0x45d + i), sPortTemp);
                                }
                                else if (nDaymode == 3)
                                {
                                    nValue = await GetGammaRegister($"RAW_GammaList_Midnight_{i}");//SerialSend.ReadRegister((ulong)(0x80140000 | 0x49e + i), sPortTemp);
                                }
                                //新增逻辑读的同时将当前2000下地址下发到8030下
                                await SetGammaRegister($"RAW_GammaList_{i}", (uint)nValue);
                                //给list 赋值
                                AddGammaPoint(i, (int)nValue);
                            }
                            break;
                        case 2:
                            {
                                
                                nValue = await GetGammaRegister($"YUV_GammaList_{i}");// SerialSend.ReadRegister((ulong)(0x80300000 | 0x900 + i), sPortTemp);
                                //给list 赋值
                                AddGammaPoint(i, (int)nValue);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            int[] arrList ={0,2,4,6,8,10,12,14,16,
                        18,20,22,24,26,28,30,32,
                        34,36,38,40,42,44,46,48,
                        50,52,54,56,58,60,62,64,
                        68,72,76,80,84,88,92,96,
                        100,104,108,112,116,120,124,128,
                        136,144,152,160,168,176,184,192,
                        200,208,216,224,232,240,248,254};
            ser.Points.Clear();
            for (int i = 0; i < listucs.Count; i++)
            {
               
                {
                    ser.Points.AddXY(listucs[i].xValue, listucs[i].yValue);
                    ser.Points[i].MarkerColor = listucs[i].Col;
                }

            }
           
            var nTemp = await GetGammaRegister("RGB_Gamma_En");//SerialSend.ReadRegister((0x80300000), sPortTemp);
            if ((nTemp & 0x40) == 0x40)
            {  //选择rgb gamma使能
                gammaStateEn.Items[0].CheckState = CheckState.Checked;
            }
            else
            {
                gammaStateEn.Items[0].CheckState = CheckState.Unchecked;
            }
            if ((nTemp & 0x20) == 0x20)
            {  //选择raw gamma使能
                gammaStateEn.Items[1].CheckState = CheckState.Checked;
            }
            else
            {
                gammaStateEn.Items[1].CheckState = CheckState.Unchecked;
            }
            nTemp = await GetGammaRegister("YUV_Gamma_En");//SerialSend.ReadRegister((0x80300000), sPortTemp);
            if ((nTemp & 0x8) == 0x8)
            {  //选择rgb gamma使能
                gammaStateEn.Items[2].CheckState = CheckState.Checked;
            }
            else
            {
                gammaStateEn.Items[2].CheckState = CheckState.Unchecked;
            }
            if (nDaymode == 0)
            {
                shadow_h_gain.Text =( await GetGammaRegister("shadow_h_gain")).ToString("X2"); //SerialSend.ReadRegister((0x80301450), sPortTemp).ToString("X2");
                tone_h_gain.Text =( await GetGammaRegister("tone_h_gain")).ToString("X2"); //SerialSend.ReadRegister((0x80301452), sPortTemp).ToString("X2");
                light_h_gain.Text =( await GetGammaRegister("light_h_gain")).ToString("X2"); //.ToString("X2");
            }
            else if (nDaymode == 1)
            {
                shadow_h_gain.Text = (await GetGammaRegister("shadow_h_gain_Day")).ToString("X2"); //SerialSend.ReadRegister((0x801404df), sPortTemp).ToString("X2");
                tone_h_gain.Text = (await GetGammaRegister("tone_h_gain_Day")).ToString("X2"); //SerialSend.ReadRegister((0x801404e0), sPortTemp).ToString("X2");
                light_h_gain.Text = (await GetGammaRegister("light_h_gain_Day")).ToString("X2"); // SerialSend.ReadRegister((0x801404e1), sPortTemp).ToString("X2");
            }
            else if (nDaymode == 2)
            {
                shadow_h_gain.Text = (await GetGammaRegister("shadow_h_gain_Night")).ToString("X2"); // SerialSend.ReadRegister((0x801404e2), sPortTemp).ToString("X2");
                tone_h_gain.Text = (await GetGammaRegister("tone_h_gain_Night")).ToString("X2"); //SerialSend.ReadRegister((0x801404e3), sPortTemp).ToString("X2");
                light_h_gain.Text = (await GetGammaRegister("light_h_gain_Night")).ToString("X2"); // SerialSend.ReadRegister((0x801404e4), sPortTemp).ToString("X2");
            }
            else if (nDaymode == 3)
            {
                shadow_h_gain.Text = (await GetGammaRegister("shadow_h_gain_Midnight")).ToString("X2"); //SerialSend.ReadRegister((0x801404e5), sPortTemp).ToString("X2");
                tone_h_gain.Text = (await GetGammaRegister("tone_h_gain_Midnight")).ToString("X2"); //SerialSend.ReadRegister((0x801404e6), sPortTemp).ToString("X2");
                light_h_gain.Text = (await GetGammaRegister("light_h_gain_Midnight")).ToString("X2"); //SerialSend.ReadRegister((0x801404e7), sPortTemp).ToString("X2");
            }
            RefreshChart();
            simpleButton6_Click(null, null);
            isRead = false;
            WaitBefore.Close();
           
        }

        #endregion


        #region ADB异步读写


        /// <summary>
        /// 异步读取单个寄存器并更新文本框
        /// </summary>
        private async Task ReadRegisterAndUpdateTextAsync(string address, TextEdit textEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");

                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    string processedValue = record.Values;
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    Console.WriteLine($"[ADBForm] 成功读取寄存器 {address} 值: {processedValue}");

                    // 处理位操作
                    string displayValue;
                    if (processedValue != "0")
                    {
                        var uintValue = BitsHelp.GetBitsToUint(bits, hex, processedValue);
                        displayValue = uintValue.ToString("X");
                        Console.WriteLine($"[ADBForm] 寄存器 {address} Bits处理后值: {displayValue} (bits:{bits}, hex:{hex})");
                    }
                    else
                    {
                        displayValue = "0";
                    }

                    // 更新UI
                    UpdateTextEdit(textEdit, displayValue);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    UpdateTextEdit(textEdit, "0");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 异步读取多个寄存器并组合更新文本框
        /// </summary>
        private async Task ReadMultipleRegistersAndUpdateTextAsync(List<addressregister> nList, TextEdit textEdit)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取多个寄存器，数量: {nList.Count}");

                string combinedValue = string.Empty;

                // 按预定义的优先级顺序读取寄存器
                var priorityOrder = new[] { "_h", "_m0", "_m1", "_m2", "_m3", "_l" };

                foreach (var priority in priorityOrder)
                {
                    addressregister register = FindRegisterByPriority(nList, priority);

                    if (register != null)
                    {
                        Console.WriteLine($"[ADBForm] 读取优先级 '{priority}' 的寄存器: {register.NameType} ({register.Address})");

                        // 发送读取命令
                        string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{register.Address},0,0\"";
                        adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{register.Address}");

                        // 等待命令执行
                        await Task.Delay(10);

                        // 获取寄存器值
                        var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(register.Address, "Read", 500));

                        if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                        {
                            string processedValue = record.Values;
                            if (processedValue.StartsWith("0x"))
                            {
                                processedValue = processedValue.Substring(2);
                            }

                            combinedValue += processedValue.PadLeft(2, '0');
                            Console.WriteLine($"[ADBForm] 成功读取 {register.Address}，当前组合值: {combinedValue}");
                        }
                        else
                        {
                            combinedValue += "00";
                            Console.WriteLine($"[ADBForm] 读取 {register.Address} 失败，使用默认值00，当前组合值: {combinedValue}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 未找到包含 '{priority}' 的寄存器");
                    }
                }

                Console.WriteLine($"[ADBForm] 最终组合值: {combinedValue}");

                // 更新UI
                UpdateTextEdit(textEdit, combinedValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取多个寄存器失败: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 根据优先级查找寄存器
        /// </summary>
        private addressregister FindRegisterByPriority(List<addressregister> nList, string priority)
        {
            if (priority == "_l")
            {
                // 特殊处理 _l 寄存器
                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                {
                    // 首先查找以 "_l" 结尾的寄存器
                    var exactMatch = nList.Find(c => c.NameType.ToLower().EndsWith("_l"));
                    if (exactMatch != null)
                    {
                        Console.WriteLine($"[ADBForm] 找到以 '_l' 结尾的寄存器: {exactMatch.NameType}");
                        return exactMatch;
                    }
                    else
                    {
                        // 如果没有以 "_l" 结尾的，则使用最后一个包含 "_l" 的寄存器
                        var containsMatch = nList.Last(c => c.NameType.ToLower().Contains("_l"));
                        Console.WriteLine($"[ADBForm] 找到包含 '_l' 的寄存器: {containsMatch.NameType}");
                        return containsMatch;
                    }
                }
            }
            else
            {
                // 其他寄存器正常处理
                var register = nList.Find(c => c.NameType.ToLower().Contains(priority));
                if (register != null)
                {
                    Console.WriteLine($"[ADBForm] 找到包含 '{priority}' 的寄存器: {register.NameType}");
                    return register;
                }
            }

            return null;
        }

        /// <summary>
        /// 更新文本框的辅助方法
        /// </summary>
        private void UpdateTextEdit(TextEdit textEdit, string value)
        {
            if (textEdit.InvokeRequired)
            {
                textEdit.Invoke(new Action(() =>
                {
                    textEdit.Text = value;
                    Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
                }));
            }
            else
            {
                textEdit.Text = value;
                Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
            }
        }

        /// <summary>
        /// 异步读取寄存器并更新复选框
        /// </summary>
        private async Task ReadRegisterAndUpdateCheckAsync(string address, CheckEdit checkEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器并更新复选框: {address}");

                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                bool isChecked = false;
                if (!string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    isChecked = BitsHelp.GetBitsCheckedToBool(bits, hex, record.Values) == 0;
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值:{record.Values}, 状态:{isChecked}");
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值无效, 状态:false");
                }

                // 更新UI
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = isChecked));
                }
                else
                {
                    checkEdit.Checked = isChecked;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 更新复选框失败: {ex.Message}");
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = false));
                }
                else
                {
                    checkEdit.Checked = false;
                }
            }
        }

        /// <summary>
        /// 异步读取单个寄存器返回值
        /// </summary>
        private async Task<long> ReadRegisterAsync(string address)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");
                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    return Convert.ToInt32(record.Values, 16);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                return 0;
            }
        }
        /// <summary>
        /// 异步写入单个寄存器，在值不匹配时自动重试一次
        /// </summary>
        private async Task<bool> WriteRegisterAsync(string address, string value)
        {
            int maxRetries = 1; // 值不匹配时最多重试一次
            int retryCount = 0;

            while (retryCount <= maxRetries)
            {
                try
                {
                    if (retryCount > 0)
                    {
                        Console.WriteLine($"[ADBForm] 第 {retryCount} 次重试写入寄存器: {address} 值: {value}");
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 开始写入寄存器: {address} 值: {value}");
                    }

                    // 处理位操作（如果有）
                    string processedValue = value;

                    // 确保值是十六进制格式（不带0x前缀）
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    // 发送写入命令
                    string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{address},{processedValue},0\"";
                    adbService.ExecuteAdbCommandAsync(adbCommand, $"写操作 - 地址:{address} 值:{processedValue}");

                    // 等待命令执行
                    await Task.Delay(10);

                    // 验证写入是否成功 - 等待写入记录出现
                    var writeRecord = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Write", 500));

                    if (writeRecord != null && !string.IsNullOrEmpty(writeRecord.Values))
                    {
                        string actualValue = writeRecord.Values;
                        if (actualValue.StartsWith("0x"))
                        {
                            actualValue = actualValue.Substring(2);
                        }

                        // 比较写入的值是否匹配
                        bool success = string.Equals(actualValue, processedValue, StringComparison.OrdinalIgnoreCase);

                        if (success)
                        {
                            Console.WriteLine($"[ADBForm] 成功写入寄存器 {address} 值: {processedValue}");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine($"[ADBForm] 写入寄存器 {address} 值不匹配，期望: {processedValue}，实际: {actualValue}");

                            // 如果不匹配且还有重试次数，则继续重试
                            if (retryCount < maxRetries)
                            {
                                retryCount++;
                                Console.WriteLine($"[ADBForm] 准备重试写入...");
                                continue; // 直接进入下一次循环，重新发送命令
                            }
                            else
                            {
                                Console.WriteLine($"[ADBForm] 写入寄存器 {address} 重试次数已用完，仍然不匹配");
                                return false;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 写入寄存器 {address} 失败，未找到写入确认记录");

                        // 如果未找到记录且还有重试次数，则重试
                        if (retryCount < maxRetries)
                        {
                            retryCount++;
                            Console.WriteLine($"[ADBForm] 准备重试写入...");
                            continue;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ADBForm] 写入寄存器 {address} 异常: {ex.Message}");

                    // 如果异常且还有重试次数，则重试
                    if (retryCount < maxRetries)
                    {
                        retryCount++;
                        Console.WriteLine($"[ADBForm] 准备重试写入...");
                        await Task.Delay(10); // 异常后稍作延迟再重试
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return false; // 理论上不会执行到这里
        }




        #endregion





        void AddGammaPoint(int x, int y) {

           
            int[] arrList ={0,2,4,6,8,10,12,14,16,
                        18,20,22,24,26,28,30,32,
                        34,36,38,40,42,44,46,48,
                        50,52,54,56,58,60,62,64,
                        68,72,76,80,84,88,92,96,
                        100,104,108,112,116,120,124,128,
                        136,144,152,160,168,176,184,192,
                        200,208,216,224,232,240,248,254};
            //if (x==0x40&& y == 255)
            //{
            //    list.Add(new ucsDouble() { xValue = 255, yValue = 255,Col = Color.Black });
            //    //list_64[0x40] = 255;
            //}
            //else {
                //list_64[x] = y;
                if (arrList[x] == 254)
                {
                //list.Add(new ucsDouble() { xValue = arrList[x], yValue = y, Col = Color.Black });
                listucs.Add(new ucsDouble() { xValue = 255, yValue = 255, Col = Color.Black });
                }
                else {
                listucs.Add(new ucsDouble() { xValue = arrList[x], yValue = y, Col = Color.Black });
                }
            //}
            listucs = listucs.Distinct(new ModelComparer()).ToList();
            //list.Distinct(new )
        }

       

        #region 选择GAMMAPRE
        /// <summary>
        /// 选择GAMMAPRE
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void COMBO_GAMMAPRE_EditValueChanged(object sender, EventArgs e)
        {
            if (IsUsbOpen || m_open)
            {

            }
            else
            {
                if (!sPortTemp.IsOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
            }
            var gamma_setting = string.Empty;
            switch (gamma_curve.SelectedIndex)
            {
                case 0: { //rgb
                        if (COMBO_GAMMAPRE.EditValue.ToString() == "0")
                        {
                            gamma_setting = string.Format("{0}\\LibGama\\rgb_gamma_setting_0.txt", Application.StartupPath);
                        }
                        if (COMBO_GAMMAPRE.EditValue.ToString() == "1")
                        {
                            gamma_setting = string.Format("{0}\\LibGama\\rgb_gamma_setting_1.txt", Application.StartupPath);
                        }
                        if (COMBO_GAMMAPRE.EditValue.ToString() == "2")
                        {
                            gamma_setting = string.Format("{0}\\LibGama\\rgb_gamma_setting_2.txt", Application.StartupPath);
                        }
                    }
                    break;
                case 1: {//raw
                        if (COMBO_GAMMAPRE.EditValue.ToString() == "0")
                        {
                            gamma_setting = string.Format("{0}\\LibGama\\raw_gamma_setting_0.txt", Application.StartupPath);
                        }
                        if (COMBO_GAMMAPRE.EditValue.ToString() == "1")
                        {
                            gamma_setting = string.Format("{0}\\LibGama\\raw_gamma_setting_1.txt", Application.StartupPath);
                        }
                        if (COMBO_GAMMAPRE.EditValue.ToString() == "2")
                        {
                            gamma_setting = string.Format("{0}\\LibGama\\raw_gamma_setting_2.txt", Application.StartupPath);
                        }
                    } break;
                case 2:
                    {//raw
                        if (COMBO_GAMMAPRE.EditValue.ToString() == "0")
                        {
                            gamma_setting = string.Format("{0}\\LibGama\\yuv_gamma_setting_0.txt", Application.StartupPath);
                        }
                        if (COMBO_GAMMAPRE.EditValue.ToString() == "1")
                        {
                            gamma_setting = string.Format("{0}\\LibGama\\yuv_gamma_setting_1.txt", Application.StartupPath);
                        }
                        if (COMBO_GAMMAPRE.EditValue.ToString() == "2")
                        {
                            gamma_setting = string.Format("{0}\\LibGama\\yuv_gamma_setting_2.txt", Application.StartupPath);
                        }
                    }
                    break;
            }
            ///下发数据
            if (!string.IsNullOrEmpty(gamma_setting))
            {
                var FList = File.ReadLines(gamma_setting);
                foreach (var item in FList)
                {
                    if (item.Contains("//"))//去除注释
                    {
                        continue;
                    }
                    var strTemp = item.Replace('，', ',').Replace("0x", "").Replace(" ", "");//全换成英文逗号，去掉0x和空格
                    string[] strArrayTemp = strTemp.Split(',');
                    if (strArrayTemp.Length > 2)
                    {
                        if (strArrayTemp[0].Trim() == "fffe") continue;
                        var addr = 0x80300000;
                        var reg_address = addr + (Convert.ToUInt32(strArrayTemp[0].Trim(), 16) & 0xffff);
                        SerialSend.WriteRegister(reg_address, (ulong)Convert.ToInt32(strArrayTemp[1], 16), sPortTemp);
                    }
                }
            }
            

           
            //重新get
            simpleButton5_Click(null, null);
        } 
       
        
        
        #endregion
        #region 方向键使用
        /// <summary>
        /// 向上
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton4_Click(object sender, EventArgs e)
        {   //使用显示出来的xy坐标
            if (string.IsNullOrEmpty(GAMMA_X.Text) || string.IsNullOrEmpty(GAMMA_Y.Text)) return;
            listucs.ForEach(c => {
                if (c.xValue.ToString() == GAMMA_X.Text && c.yValue <=double.Parse( GAMMA_Y.Text))
                {
                    c.yValue += 1;
                    if (c.yValue > 255)
                    {
                        c.yValue = 255;
                    }
                    GAMMA_Y.Text = c.yValue.ToString();
                }
            });
            RefreshChart();
        }
        /// <summary>
        /// 向左
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(GAMMA_X.Text) || string.IsNullOrEmpty(GAMMA_Y.Text)) return;
            listucs.ForEach(c => {
                if (c.xValue.ToString() == GAMMA_X.Text&&c.yValue.ToString() == GAMMA_Y.Text)
                {                   
                    c.xValue -= 1;
                    if (c.xValue<1)
                    {
                        c.xValue = 1;
                    }
                    GAMMA_X.Text = c.xValue.ToString();
                }
            });
            RefreshChart();
        }
        /// <summary>
        /// 向右
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(GAMMA_X.Text) || string.IsNullOrEmpty(GAMMA_Y.Text)) return;
            listucs.ForEach(c => {
                if (c.xValue.ToString() == GAMMA_X.Text && c.yValue.ToString() == GAMMA_Y.Text)
                {
                    c.xValue += 1;
                    if (c.xValue>255)
                    {
                        c.xValue = 255;
                    }
                    GAMMA_X.Text = c.xValue.ToString();
                }
            });
            RefreshChart();
        }
        /// <summary>
        /// 向下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(GAMMA_X.Text) || string.IsNullOrEmpty(GAMMA_Y.Text)) return;
            listucs.ForEach(c => {
                if (c.xValue.ToString() == GAMMA_X.Text && c.yValue >= double.Parse( GAMMA_Y.Text))
                {
                    c.yValue -= 1;
                    if (c.yValue < 0)
                    {
                        c.yValue = 0;
                    }
                    GAMMA_Y.Text = c.yValue.ToString();
                }
            });
            RefreshChart();
        }
        #endregion

        private async void checkedListBoxControl1_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (isRead) return;

            var nTemp1 = await GetAERegister("Scene_Switch_En");
            var nTemp2 = await GetAERegister("Debug_En");
            switch (checkedListBoxControl1.SelectedIndex)
            {
                //Scence Switch En 
                case 0:
                    {
                        if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
                        {
                            //SetAeRegister("Scene_Switch_En", (ulong)(nTemp1 | 0x04));
                            await SetAeRegister("Scene_Switch_En", 0x12);
                            checkedListBoxControl1.Items[1].Enabled = true;
                            if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
                            {
                                DayMode.Enabled = true;
                            }
                        }
                        else  //S不勾选
                        {
                            //SetAeRegister("Scene_Switch_En", (ulong)(nTemp1 & 0xfb));
                            await SetAeRegister("Scene_Switch_En", 0x00);
                            checkedListBoxControl1.Items[1].Enabled = false;
                            DayMode.Enabled = false;
                        }

                    }
                    break;
                // Debug en
                case 1:
                    {
                        if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
                        {
                            await SetAeRegister("Debug_En", (ulong)(nTemp2 & 0xfd));
                            if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
                            {
                                DayMode.Enabled = true;
                            }
                        }
                        else//D不勾选
                        {
                            await SetAeRegister("Debug_En", (ulong)(nTemp2 | 0x02));
                            DayMode.Enabled = false;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        private async void DayMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isRead) return;            
            switch (DayMode.SelectedIndex)
            {
                case 0:
                    radiostr = "_Day";
                    await SetAeRegister("Scene_Mode", 0x00);
                    isRead = true;
                    shadow_h_gain.Text =(await GetGammaRegister("shadow_h_gain_Day")).ToString("X2"); //SerialSend.ReadRegister((0x80301450), sPortTemp).ToString("X2");
                    tone_h_gain.Text = (await GetGammaRegister("tone_h_gain_Day")).ToString("X2"); //SerialSend.ReadRegister((0x80301452), sPortTemp).ToString("X2");
                    light_h_gain.Text = (await GetGammaRegister("light_h_gain_Day")).ToString("X2");
                    break;
                case 1:
                    radiostr = "_Night";
                    await SetAeRegister("Scene_Mode", 0x01);
                    isRead = true;
                    shadow_h_gain.Text = (await GetGammaRegister("shadow_h_gain_Night")).ToString("X2"); //SerialSend.ReadRegister((0x80301450), sPortTemp).ToString("X2");
                    tone_h_gain.Text = (await GetGammaRegister("tone_h_gain_Night")).ToString("X2"); //SerialSend.ReadRegister((0x80301452), sPortTemp).ToString("X2");
                    light_h_gain.Text = (await GetGammaRegister("light_h_gain_Night")).ToString("X2");
                    break;
                case 2:
                    radiostr = "_Midnight";
                    await SetAeRegister("Scene_Mode", 0x02);
                    isRead = true;
                    shadow_h_gain.Text = (await GetGammaRegister("shadow_h_gain_Midnight")).ToString("X2"); //SerialSend.ReadRegister((0x80301450), sPortTemp).ToString("X2");
                    tone_h_gain.Text = (await GetGammaRegister("tone_h_gain_Midnight")).ToString("X2"); //SerialSend.ReadRegister((0x80301452), sPortTemp).ToString("X2");
                    light_h_gain.Text = (await GetGammaRegister("light_h_gain_Midnight")).ToString("X2");
                    break;
                default:
                    radiostr = "";
                    isRead = true;
                    shadow_h_gain.Text = (await GetGammaRegister("shadow_h_gain")).ToString("X2"); //SerialSend.ReadRegister((0x80301450), sPortTemp).ToString("X2");
                    tone_h_gain.Text = (await GetGammaRegister("tone_h_gain")).ToString("X2"); //SerialSend.ReadRegister((0x80301452), sPortTemp).ToString("X2");
                    light_h_gain.Text = (await GetGammaRegister("light_h_gain")).ToString("X2");
                    break;
            }
            isRead = false;
           
           
        }

        private async void simpleButton6_Click(object sender, EventArgs e)
        {              
            //long m_nDayMode;
            isRead = true;

            long nMask = ((await GetAERegister("Scene_Mode")) & 0x3);
            if (nMask == 0)
            {
                DayMode.SelectedIndex = 0;
            }
            else if (nMask == 1)
            {
                DayMode.SelectedIndex = 1;
            }
            else if (nMask == 2)
            {
                DayMode.SelectedIndex = 2;
            }
            //Scene_Switch_En

            if (((await GetAERegister("Scene_Switch_En")) & 0x12) == 0x12)
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Checked;
                checkedListBoxControl1.Items[1].Enabled = true;
            }
            else
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Unchecked;
                checkedListBoxControl1.Items[1].Enabled = false;
                DayMode.Enabled = false;
            }
            //Debug_En
           
            if (((await GetAERegister("Debug_En")) & 0x02) == 0x00)
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Checked;
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)
                {
                    DayMode.Enabled = true;
                }
            }
            else
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Unchecked;
                DayMode.Enabled = false;
            }
            isRead = false;
        
        }

        private async void gammaStateEn_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (isRead) return;
            switch (gammaStateEn.SelectedIndex)
            {
                case 0: {
                        if (gammaStateEn.Items[0].CheckState == CheckState.Checked)
                        {
                            var nValue =await GetGammaRegister("RGB_Gamma_En");
                            await SetGammaRegister("RGB_Gamma_En", (ulong)(nValue | 0x40));
                           
                        }
                        else {
                            var nValue = await GetGammaRegister("RGB_Gamma_En");
                            await SetGammaRegister("RGB_Gamma_En", (ulong)(nValue & 0xBF));
                           
                        }
                    } break;
                case 1: {
                        if (gammaStateEn.Items[1].CheckState == CheckState.Checked)
                        {
                            var nValue = await GetGammaRegister("RAW_Gamma_En");
                            await SetGammaRegister("RAW_Gamma_En", (ulong)(nValue | 0x20));
                           
                        }
                        else {
                            var nValue = await GetGammaRegister("RAW_Gamma_En");
                            await SetGammaRegister("RAW_Gamma_En", (ulong)(nValue & 0xDF));
                           
                        }
                    } break;
                case 2:
                    {
                        if (gammaStateEn.Items[2].CheckState == CheckState.Checked)
                        {
                            var nValue = await GetGammaRegister("YUV_Gamma_En");
                            await SetGammaRegister("YUV_Gamma_En", (ulong)(nValue | 0x8));

                        }
                        else
                        {
                            var nValue = await GetGammaRegister("YUV_Gamma_En");
                            await SetGammaRegister("YUV_Gamma_En", (ulong)(nValue & 0xF7));

                        }
                        if (XChipGamma.Exists(c => c.NameType.ToLower() == ("ygamma_clk_en").ToLower()))
                        {
                            var model = XChipGamma.Find(c => c.NameType.ToLower() == ("ygamma_clk_en").ToLower());
                            var Add = await ReadRegisterAsync(model.Address);
                            var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), gammaStateEn.Items[2].CheckState == CheckState.Checked);
                            await SetGammaRegister(model, Val);
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        private void gamma_curve_SelectedIndexChanged(object sender, EventArgs e)
        {
            //重新get
            simpleButton5_Click(null, null);
        }


        
      
        /// <summary>
        /// 下发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton8_Click(object sender, EventArgs e)
        {
           

            //保存到数据库中
            var listTemp = new List<ucsDouble>();
            int[] arrList ={0,2,4,6,8,10,12,14,16,
                           18,20,22,24,26,28,30,32,
                           34,36,38,40,42,44,46,48,
                           50,52,54,56,58,60,62,64,
                           68,72,76,80,84,88,92,96,
                           100,104,108,112,116,120,124,128,
                           136,144,152,160,168,176,184,192,
                           200,208,216,224,232,240,248,254};
            for (int i = 0; i < 65; i++)
            {
                listTemp.Add(new ucsDouble() { xValue = arrList[i], yValue = (int)list_64[i] , Col=Color.Black});
            }
            gammahistory model = new gammahistory();
            model.CreateName = DateTime.Now.ToString("HH:mm:sss");
            model.CreationTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss");
            model.HistoryTxt = JsonConvert.SerializeObject(listTemp);
            gammaM.Insert(model);

            //刷新选择框
            LookHistory.Properties.ValueMember = "ID";
            LookHistory.Properties.DisplayMember = "CreateName";
            LookHistory.Properties.DataSource = gammaM.GetList(c => c.CreationTime.Contains($"{DateTime.Now.ToString("yyyy-MM-dd")}")).OrderByDescending(c => c.ID);
            LookHistory.Refresh();

            //下发看看正确性
            for (int i = 0; i < list_64.Count(); i++)
            {
                switch (gamma_curve.SelectedIndex)
                {
                    case 0:
                        {
                            switch (DayMode.SelectedIndex)
                            {
                                case 0: { SetGammaRegister($"RGB_GammaList_Day_{i}", (ulong)(list_64[i])); } break;
                                case 1: { SetGammaRegister($"RGB_GammaList_Night_{i}", (ulong)(list_64[i])); } break;
                                case 2: { SetGammaRegister($"RGB_GammaList_Midnight_{i}", (ulong)(list_64[i])); } break;
                                default: { SetGammaRegister($"RGB_GammaList_{i}", (ulong)(list_64[i])); } break;
                                   
                            }
                            SetGammaRegister($"RGB_GammaList_{i}", (ulong)(list_64[i]));
                           
                        }
                        break;
                    case 1:
                        {
                            switch (DayMode.SelectedIndex)
                            {
                                case 0: { SetGammaRegister($"RAW_GammaList_Day_{i}", (ulong)(list_64[i])); } break;
                                case 1: { SetGammaRegister($"RAW_GammaList_Night_{i}", (ulong)(list_64[i])); } break;
                                case 2: { SetGammaRegister($"RAW_GammaList_Midnight_{i}", (ulong)(list_64[i])); } break;
                                default: { SetGammaRegister($"RAW_GammaList_{i}", (ulong)(list_64[i])); } break;
                                   
                            }
                            SetGammaRegister($"RAW_GammaList_{i}", (ulong)(list_64[i]));

                        }
                        break;
                    case 2:
                        {
                            SetGammaRegister($"YUV_GammaList_{i}", (ulong)(list_64[i]));

                        }
                        break;
                    default:
                        break;
                }
            }
        }

        private void chart1_MouseLeave(object sender, EventArgs e)
        {
            return;
        }

        private void chart1_GetToolTipText(object sender, ToolTipEventArgs e)
        {
            if (e.HitTestResult.ChartElementType == ChartElementType.DataPoint)
            {
                int i = e.HitTestResult.PointIndex;
                DataPoint dp = e.HitTestResult.Series.Points[i];
                //分别显示x轴和y轴的数值，其中{1:F3},表示显示的是float类型，精确到小数点后3位。   
                if (dp.XValue == 0|| dp.XValue == 32 || dp.XValue == 64 || dp.XValue == 96 || dp.XValue == 128 || dp.XValue == 160 || dp.XValue == 192 || dp.XValue == 224||dp.XValue ==255)
                {
                    e.Text = string.Format("参考点位无法删除 \n X值:{0};Y值:{1} ", dp.XValue, dp.YValues[0]);
                }
                else {
                    e.Text = string.Format("X值:{0};Y值:{1} ", dp.XValue, dp.YValues[0]);
                }
                
            }
        }
        /// <summary>
        /// 选择框更改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LookHistory_EditValueChanged(object sender, EventArgs e)
        {
            string daID = this.LookHistory.EditValue.ToString();
            var model =  gammaM.GetSingle(c => c.ID == int.Parse( daID));
            listucs.Clear();
            listucs = JsonConvert.DeserializeObject<List<ucsDouble>>(model.HistoryTxt);
            var ser = chart1.Series[0];
            ser.Points.Clear();
            int count=0;
            //刷新图像
            for (int i = 0; i < listucs.Count; i++)
            {
                if (i == 0 || i == 0x8 || i == 0x10 || i == 0x18 || i == 0x20 || i == 0x28 || i == 0x30 || i == 0x38 || i == 0x40)
                {
                    ser.Points.AddXY(listucs[i].xValue, listucs[i].yValue);
                    //Col   Color.BlanchedAlmond
                    ser.Points[count].MarkerColor = listucs[i].Col;
                    count++;
                }
            }
            

        }
        private async Task<long> GetAERegister(string nameType)
        {
           
            if (XChipAe.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                long var = await ReadRegisterAsync(XChipAe.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address);
                return var;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }
        private async Task SetAeRegister(string nameType, ulong add)
        {
            if (isRead) return;

            var model = XChipAe.Find(c => c.NameType.ToLower() == (nameType).ToLower());
            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetCfaRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }


        }
        private async Task SetGammaRegister(string nameType, ulong add)
        {
           
            if (isRead) return;

            var model = XChipGamma.Find(c => c.NameType.ToLower() == (nameType).ToLower());
            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetGammaRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }

        }
        private async Task SetGammaRegister(addressregister model, ulong add, bool isCheck = true)
        {
           
            if (isRead) return;

          
            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetCfaRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }
        }
        private async Task<long> GetGammaRegister(string nameType)
        {
           
            if (XChipGamma.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                long var = await ReadRegisterAsync(XChipGamma.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address);
                return var;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }

        private async void SHADOWHGAIN_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (isRead) return;
            //if (string.IsNullOrEmpty(shadow_h_gain.Text)) return;
            //SerialSend.WriteRegister(0x80301450, (ulong)Convert.ToInt32(shadow_h_gain.Text, 16), sPortTemp); if (isWrite) return;
            if (isRead)//判断是否在读，读的时候不进行写
            {
                return;
            }
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (XChipGamma.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}".ToLower()))
            {
                var model = XChipGamma.Find(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                await SetGammaRegister(model, Val);
                isRead = true;
                txtEdit.Text = Val.ToString("X2");
                isRead = false;
            }
            switch (DayMode.SelectedIndex)
            {
                case 0:
                case 1:
                case 2:
                    {
                        if (XChipGamma.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}{radiostr.ToLower()}".ToLower()))
                        {
                            var model = XChipGamma.Find(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}{radiostr.ToLower()}".ToLower());
                            var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                            await SetGammaRegister(model, Val);
                        }
                    }
                    break;
                default:
                    {

                    }
                    break;
            }

        }

        private async void TONEHGAIN_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (isRead) return;
            //if (string.IsNullOrEmpty(tone_h_gain.Text)) return;
            //SerialSend.WriteRegister(0x80301452, (ulong)Convert.ToInt32(tone_h_gain.Text, 16), sPortTemp);
            //switch (DayMode.SelectedIndex)
            //{
            //    case 0:
            //        {//GAMMA_DAYMODE
            //            SerialSend.WriteRegister(0x801405a4, (ulong)Convert.ToInt32(tone_h_gain.Text, 16), sPortTemp);
            //        }
            //        break;
            //    case 1:
            //        {//GAMMA_NIGHTMODE
            //            SerialSend.WriteRegister(0x801405a7, (ulong)Convert.ToInt32(tone_h_gain.Text, 16), sPortTemp);
            //        }
            //        break;
            //    case 2:
            //        {//GAMMA_MIDNIGHTMODE
            //            SerialSend.WriteRegister(0x801405aa, (ulong)Convert.ToInt32(tone_h_gain.Text, 16), sPortTemp);
            //        }
            //        break;
            //    default:
            //        {

            //        }
            //        break;
            //}
            if (isRead)//判断是否在读，读的时候不进行写
            {
                return;
            }
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (XChipGamma.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}".ToLower()))
            {
                var model = XChipGamma.Find(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                await SetGammaRegister(model, Val);
                isRead = true;
                txtEdit.Text = Val.ToString("X2");
                isRead = false;
            }
            switch (DayMode.SelectedIndex)
            {
                case 0:
                case 1:
                case 2:
                    {
                        if (XChipGamma.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}{radiostr.ToLower()}".ToLower()))
                        {
                            var model = XChipGamma.Find(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}{radiostr.ToLower()}".ToLower());
                            var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                            await SetGammaRegister(model, Val);
                        }
                    }
                    break;
                default:
                    {

                    }
                    break;
            }
        }

        private async void LIGHTHGAIN_Leave(object sender, EventArgs e)
        {
           
            if (isRead)//判断是否在读，读的时候不进行写
            {
                return;
            }
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (XChipGamma.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}".ToLower()))
            {
                var model = XChipGamma.Find(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}".ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                await SetGammaRegister(model, Val);
                isRead = true;
                txtEdit.Text = Val.ToString("X2");
                isRead = false;
            }
            switch (DayMode.SelectedIndex)
            {
                case 0:
                case 1:
                case 2:
                    {
                        if (XChipGamma.Exists(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}{radiostr.ToLower()}".ToLower()))
                        {
                            var model = XChipGamma.Find(c => c.NameType.ToLower() == $"{txtEdit.Name.ToLower()}{radiostr.ToLower()}".ToLower());
                            var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                           await SetGammaRegister(model, Val);
                        }
                    }
                    break;
                default:
                    {

                    }
                    break;
            }
        }

        private async void simpleButton9_Click(object sender, EventArgs e)
        {
            if (IsUsbOpen || m_open)
            {

            }
            else
            {
                if (!sPortTemp.IsOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
            }
            //SerialSend.isDebug = false;
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "配置文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "IQ_Setting_Gamma_" + DateTime.Now.ToString("yyyyMMddHHmms");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                //StringBuilder sb = new StringBuilder();
                var Pe_dal = new parameter_exportManager();
                if (null != Pe_dal)
                {
                    WaitBefore.Start("参数导出", "正在加载中", 60);

                  
                    var tempList = Pe_dal.GetListToExport().Where(c => c.Module == "RAW Gamma" || 
                    c.Module == "RGB Gamma"||
                    c.Module.Contains("RGB Gamma 0x80301400") ||
                    c.Module.Contains("RAW Gamma 0x80300900") ||
                    c.Module.Contains("RGB Gamma HF 0x80301450") ||
                    c.Module == "IQ switch enable").OrderBy(c=>c.SortNum).ToList();
                    var moduleList = tempList.Select(c => c.Module).Distinct();
                    #region 判断是否需要用白天的数据
                    var Pe_patch_dal = new parameter_export_patchManager();
                    var patchList = Pe_patch_dal.GetList();
                    var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
                    foreach (var item in conditionList)
                    {
                        if ((await ReadRegisterAsync(item)) == 0)
                        {
                            patchList.RemoveAll(c => c.ConditionAddr == item);
                        }
                    }
                    #endregion

                    var sb = XChipHelp.ReadParameterExportExpand(tempList, "80", patchList, sPortTemp);
             
                    System.IO.File.WriteAllText(sfd.FileName, sb.ToString());
                    WaitBefore.Close();
                    DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
                }
                //SerialSend.isDebug = true;
            }
        }

        private void SHADOWHGAIN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SHADOWHGAIN_Leave(sender, null);
            }
        }

        private void TONEHGAIN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TONEHGAIN_Leave(sender, null);
            }
        }

        private void LIGHTHGAIN_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                LIGHTHGAIN_Leave(sender, null);
            }
        }

        private void simpleButton10_Click(object sender, EventArgs e)
        {
            //string str = "       调节 RAW 域或 RGB 域的 Gamma 曲线，Scene_Switch使能后，勾选“调试”可分别调整Day_mode、night_mode、midnight_mode场景下的Gamma曲线。\r\n       更多详见《调试工具用户手册》。";
            Thread thread = new Thread(threadPro);
            thread.Start();
        }
        private void threadPro()

        {

            MethodInvoker methodInvoker = new MethodInvoker(ShowFormB);

            BeginInvoke(methodInvoker);

        }

        private void ShowFormB()

        {
            //string str = "\t      \t 调节 RAW 域或 RGB 域的 Gamma 曲线，Scene_Switch使能后，勾选“Debug”可分别调整Day_mode、night_mode、midnight_mode场景下的Gamma曲线。\r\n"
            //   + "\t      \t 更多详见《调试工具用户手册》。";
            //if (ConfigurationManager.AppSettings["xcEdition"] == "1")
            //{
            //    str = "\t      \t ISP分为raw gamma，rgb gamma，主要影响图像亮度，通透度，根据不同客户需求拉不同的gamma 晚上和极夜建议raw gamma（改善通透度增加噪点）不要拉太多 \r\n"
            //  + "\t      \t 边缘增强_低亮度表示低亮度的清晰度，值越大清晰度越高 \r\n"
            //  + "\t      \t 边缘增强_中亮度表示中间亮度的清晰度，值越大清晰度越高 \r\n"
            //  + "\t      \t 边缘增强_高亮度表示高亮度的清晰度，值越大清晰度越高 \r\n";
            //}
            string str = "";
            XChip_OptimizationTips ot = new XChip_OptimizationTips("Gamma调优Tips", str);
            ot.StartPosition = FormStartPosition.CenterScreen;
            //ot.ShowDialog();
            ot.Show();

        }

        private void simpleButton5_MouseEnter(object sender, EventArgs e)
        {
            isWrite = true;
        }

        private void simpleButton5_MouseLeave(object sender, EventArgs e)
        {
            isWrite = false;
        }

        private void checkedListBoxControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }


    /// <summary>
    /// 设置xy值
    /// </summary>
    public class ucsDouble
    {
        public int xValue;
        public int yValue;
        /// <summary>
        /// 颜色
        /// </summary>
        public Color Col = Color.Transparent;
    }    

}
